﻿using DTcms.Common;
using DTcms.Core.Services;
using DTcms.Web.Mvc.UI;
using System.Collections.Generic;
using System.Web.Mvc;
using System;
using System.Reflection;

namespace DTcms.Web.Mvc.WebControllers
{
    public class HomeController : BaseController
    {
        #region private items
        private ThemeService _themeService = new ThemeService();
        private Model.BaseModel _model = new Model.BaseModel();
        private int pagesize;//当前页容量 默认10
        private string channel = string.Empty;//频道名称
        #endregion

        public HomeController()
        {
            _themeService.InitTheme(site.templet_path);
        }

        [Compress]
        public ActionResult Index(string pagename)
        {
            _model.config = config;
            _model.uconfig = uconfig;
            _model.site = site;
            if (IsUserLogin())
            {
                _model.userModel = GetUserInfo();
            }
            if (string.IsNullOrEmpty(pagename))
            {
                pagename = "index";
            }
            ViewBag.Title = _model.site.title;
            ViewBag.Keywords = _model.site.seo_keywords;
            ViewBag.Description = _model.site.seo_description;
            _model.templateskin = string.Format("{0}{1}/{2}", _model.config.webpath, "templates", _model.site.templet_path);

            string type = string.Empty;//频道类型 用于区分
            string templet = string.Empty;//模板原文件 用于找到显示的页面
            string inherit = string.Empty;//继承类名
            string name = string.Empty;//标记名称
            var allUrls = SiteUrls.GetEffective(config.webpath, site.templet_path);

            foreach (Model.url_rewrite model in allUrls)
            {
                if (model.name == pagename)
                {
                    type = model.type;
                    templet = model.page.Replace(".cshtml", "");
                    name = model.name;
                    inherit = model.inherit;
                    channel = model.channel;
                    pagesize = Utils.StrToInt(model.pagesize, 10);
                }
            }
            if (string.IsNullOrEmpty(templet))
            {
                //throw new Exception("没有找到对应重写路径！");
                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("没有找到对应重写路径！")));
            }
            if (!string.IsNullOrEmpty(pagename) && pagename != "index")
            {
                if (type == "plugin")//插件页
                {
                    return Plugin(templet, inherit);//关于插件
                }
                else
                {
                    return Article(templet, inherit, type);//关于文章及会员及其他界面  文章需要传递channel
                }
            }
            else
            {
                return View(_model);
            }
        }

        #region 其他页
        public ActionResult Article(string templet, string inherit, string urlType)
        {
            _model.info = new Dictionary<string, object>();

            if (string.IsNullOrEmpty(inherit))
            {
                //throw new Exception("页面继承不能为空！");
                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("页面继承不能为空！")));
            }
            if (templet.Contains("member/"))
            {
                if (_model.userModel == null)
                {
                    return Redirect(linkurl("login"));
                }
                else
                {
                    Model.user_groups groupModel = new BLL.user_groups().Get(_model.userModel.group_id);
                    if (groupModel == null)
                    {
                        groupModel = new Model.user_groups();
                    }
                    _model.info.Add("groupModel", groupModel);
                }
            }
            try
            {
                // 1.Load(命名空间名称)，GetType(命名空间.类名)
                Type type = Assembly.Load("DTcms.Web.Mvc.UI").GetType(inherit, true);
                object obj;
                if (urlType == "index" || urlType == "list" || urlType == "detail" || urlType == "category")//判断是否是文章页  其实不用设置也可以
                {
                    site_model = new BLL.site_channel().GetCaCheModel(channel);
                    if (site_model == null)
                    {
                        //throw new Exception("频道验证错误！");
                        return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("频道验证错误！")));
                    }
                    obj = Activator.CreateInstance(type, site_model);
                    _model.info.Add("site_model", site_model);
                }
                else//其他页
                {
                    obj = Activator.CreateInstance(type, true);
                }

                if (type != null)
                {
                    BindingFlags flag = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
                    FieldInfo[] fields = type.GetFields(flag);
                    foreach (FieldInfo fi in fields)
                    {
                        string name = fi.Name;
                        var value = fi.GetValue(obj);
                        #region 进行验证
                        if (name == "redirect" && !string.IsNullOrEmpty(value.ToString()))//有错误 立即跳转错误页
                        {
                            return Redirect(value.ToString());
                        }
                        if (name == "zhuanti" && !string.IsNullOrEmpty(value.ToString()))//有专题时 修改templet 替换{0}
                        {
                            templet = string.Format(templet, value.ToString());
                        }
                        if (urlType == "list")
                        {
                            if (name == "category" && value == null)
                            {
                                //throw new Exception("类别获取错误！");
                                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("类别获取错误！")));
                            }
                        }
                        else if (urlType == "detail")
                        {
                            if (name == "article" && value == null)
                            {
                                //throw new Exception("没有获取到文章详细的信息！");
                                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("没有获取到文章详细的信息！")));
                            }
                        }
                        else if (urlType == "category")
                        {
                            if (name == "category_model" && value == null)
                            {
                                //throw new Exception("栏目列表获取错误！");
                                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("栏目列表获取错误！")));
                            }
                        }
                        #endregion
                        if (name == "page")//页码
                        {
                            _model.page = Utils.ObjToInt(value);
                        }
                        else if (name == "totalcount")//总数据条数
                        {
                            _model.totalcount = Utils.ObjToInt(value);
                        }
                        else if (name == "pagelist")//分页页码
                        {
                            _model.pagelist = value.ToString();
                        }
                        else
                        {
                            _model.info.Add(name, value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("\r\n错误记录：{0}\r\n", ex.ToString()));
                //throw new Exception("页面继承错误！");
                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("页面继承错误！")));
            }
            _model.pagesize = pagesize;
            return View(templet, _model);
        }
        #endregion

        #region 插件页
        public ActionResult Plugin(string templet, string inherit)
        {
            _model.info = new Dictionary<string, object>();
            string dirPath = inherit.Split('.')[3].ToLower();//插件目录
            if (string.IsNullOrEmpty(inherit))
            {
                //throw new Exception("页面继承不能为空！");
                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("页面继承不能为空！")));
            }
            try
            {
                // 1.Load(命名空间名称)，GetType(命名空间.类名)
                Type type = Assembly.Load(inherit.Substring(0, inherit.LastIndexOf('.'))).GetType(inherit, true);
                templet = "plugins/" + dirPath + "/" + templet;//插件读取模式 plugins/插件目录/插件页
                object obj = Activator.CreateInstance(type, true);
                if (type != null)
                {
                    BindingFlags flag = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
                    FieldInfo[] fields = type.GetFields(flag);
                    foreach (FieldInfo fi in fields)
                    {
                        string name = fi.Name;
                        var value = fi.GetValue(obj);
                        if (name == "redirect" && !string.IsNullOrEmpty(value.ToString()))//有错误 立即跳转错误页
                        {
                            return Redirect(value.ToString());
                        }
                        if (name == "page")
                        {
                            _model.page = Utils.ObjToInt(value);
                        }
                        else if (name == "totalcount")
                        {
                            _model.totalcount = Utils.ObjToInt(value);
                        }
                        else if (name == "pagelist")
                        {
                            _model.pagelist = value.ToString();
                        }
                        else
                        {
                            _model.info.Add(name, value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("\r\n错误记录：{0}\r\n", ex.ToString()));
                //throw new Exception("插件页面继承错误！");
                return Redirect(linkurl("error", "?msg=" + Utils.UrlEncode("插件页面继承错误！")));
            }
            _model.pagesize = pagesize;
            return View(templet, _model);
        }
        #endregion
    }
}